package org.hry.socket.bio.shortlink;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Desc
 * @Author houry
 * @Date 2021/2/23 17:33
 **/
public class SocketThreadFactory implements ThreadFactory {
    /**
     * 线程组
     */
    private final ThreadGroup threadGroup;
    /**
     * 线程数量初始值，这里只是展示使用
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    /**
     * 线程名前缀
     */
    public final String namePrefix;

    public SocketThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        if (null == name || "".equals(name.trim())) name = "pool";
        // 线程池数量初始值，这里只是展示使用，用作名字的拼接。
        AtomicInteger poolNumber = new AtomicInteger(1);
        namePrefix = name + "-" + poolNumber.getAndIncrement() + "-socket-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(threadGroup, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}